import type {
  PlatformPageTypeValue,
  PlatformTypeValue,
  ThemeType,
} from '../../../../types/interfaces'
import type { PageType } from '../../../page_handler/type'
import { ConfigManager } from '../../../../module/config_manager'
import { ARTICLE_LINK_RULES } from '../../../../module/page_enhancer/base/element_adapt'
import {
  APP_DOM_SELECTOR_CONFIG,
  getCurrentURL,
  logger,
  PAGE_ELEMENTS,
  PROJECT_PREFIX,
  THEME_VAR,
} from '../../../../types/constants'
import { StylesService } from '../../../../types/constants/styles'
import { createStandardStyleTag } from '../../../style_injector'
import { ToolKit } from '../../../utils/toolkit'
import { ColorService } from '../color_service'
import { ThemeVarService } from '../theme_var/service'

export abstract class BaseThemeService extends ColorService {
  protected elements: any
  abstract wrapperSelector: string // 最外层增加包裹，提高特异性
  abstract name: string
  abstract platformPageType: PlatformPageTypeValue
  protected stylesService: StylesService = StylesService.getInstance()
  protected themeVarService: ThemeVarService = ThemeVarService.getInstance()

  protected constructor(platform: PlatformTypeValue) {
    super()
    this.elements = PAGE_ELEMENTS[platform]
  }

  protected updateElementStylesForTheme(): void {}

  /**
   * 获取主题样式
   */
  protected getThemeStyles(_theme: ThemeType): string {
    return ''
  }

  /**
   * 注册主题样式
   */
  registerThemeStyles(theme: ThemeType, id: string): void {
    const themeStyles = theme ? this.getThemeStyles(theme as ThemeType) : '/* Not select any theme */'
    createStandardStyleTag(`${id}`, themeStyles, {
      allowEmpty: true,
    })
  }

  checkEnv(): void {
    this.checkWrapperSelector()
  }

  private checkWrapperSelector(): void {
    const $element = $(this.wrapperSelector)
    if (!$element || !$element.length) {
      logger.warn(`[${this.name}] 样式外层包裹选择器无效：${this.wrapperSelector}`)
    }
  }

  protected checkPageType(pageType: PageType): void {
    const configManagerPageType = ConfigManager.getInstance().pageType

    if (ConfigManager.getInstance().pageType !== pageType) {
      logger.error(`[${this.name}] 配置管理器页面类型（${configManagerPageType}）与当前页面类型 （${pageType}）不一致`)
    }
    else {
      logger.attention(`[${this.name}] 识别页面类型为：${pageType}`, getCurrentURL())
    }
  }

  protected commonStyleVar(_theme: ThemeType): string {
    return ''
  }

  protected platformStyleVar(_theme: ThemeType): string {
    return ''
  }

  getStyleVar(theme: ThemeType): string {
    ToolKit.browser.theme.setTheme(theme)

    return `:root {
  ${THEME_VAR}: ${theme};
  ${this.commonStyleVar(theme)}
  ${this.platformStyleVar(theme)}
}
`
  }

  protected scrollStyles(_theme: ThemeType) {
    return StylesService.getInstance().scroll.default
  }

  protected getCodeStyles(_theme: ThemeType): string {
    const { CONTENT_CODE } = this.elements

    if (!CONTENT_CODE || CONTENT_CODE.selector === '') {
      return ''
    }

    return `
${CONTENT_CODE.selector} {
  color: var(--${PROJECT_PREFIX}-theme-code-text-secondary) !important;
  background-color: transparent !important;
  font-size: 13px !important;
}
`
  }

  protected getLinkStyles(theme: ThemeType): string {
    const { CONTENT_LINK } = this.elements

    if (!CONTENT_LINK || CONTENT_LINK.selector === '') {
      return ''
    }

    return `
${CONTENT_LINK.selector} {
  ${this.stylesService.link.default()}
  border-bottom: 1px dashed var(--${PROJECT_PREFIX}-theme-primary) !important;
  position: relative;
  
  &:hover {
    border-bottom-style: solid;
  }
  
  ${this.LinkIconStyles(theme)}
  
  ${this.customLinkStyles(theme)}
}`
  }

  protected LinkIconStyles(theme: ThemeType) {
    return `
${ARTICLE_LINK_RULES.map(rule => `
  &[data-link-type="${rule.id}"] {
    padding-left: 20px !important;
    margin-left: 4px !important;
    white-space: nowrap !important;
    overflow: hidden !important;
    text-overflow: ellipsis !important;
    
    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 16px;
      height: 16px;
      background-image: var(${this.themeVarService.generateIcon(rule.id)});
      background-size: contain;
      background-repeat: no-repeat;
      ${theme === 'dark' ? 'opacity: 0.85;' : ''}
    }
  }`).join('\n')} 
`
  }

  protected customLinkStyles(_theme: ThemeType) {
    return ''
  }

  protected getTableStyles(_theme: ThemeType): string {
    const { CONTENT_TABLE } = this.elements

    if (!CONTENT_TABLE || CONTENT_TABLE.selector === '') {
      return ''
    }

    return `
${CONTENT_TABLE.selector} {
  width: 100% !important;
  border-collapse: collapse !important; /* 合并单元格边框 */
  border-spacing: 0 !important; /* 清除默认间隙 */
  overflow-x: auto !important;
  display: table !important;
  border: none !important;

  th, td {
    border: 1px solid var(--${PROJECT_PREFIX}-theme-table-cell-border);
    text-align: left;
  }

  th {
    background-color: var(--${PROJECT_PREFIX}-theme-table-header-bg) !important;
    color: var(--${PROJECT_PREFIX}-theme-table-heading-text) !important;
    font-size: 16px !important;
    font-weight: 600;
    position: sticky;
    top: 0;
  }
  
  tbody tr {
    &:nth-child(even) {
      background-color: var(--${PROJECT_PREFIX}-theme-table-row-even-bg) !important;
    }
    &:nth-child(odd) {
      background-color: var(--${PROJECT_PREFIX}-theme-table-row-odd-bg) !important;
    }
    &:hover {
      background-color: var(--${PROJECT_PREFIX}-theme-table-row-hover-bg) !important;
      /* 表格内容 */
      td, td p, td span, td strong, td code {
        color: var(--${PROJECT_PREFIX}-theme-table-row-hover-text) !important;
        font-size: 15px !important;
      }
    }
    /* 表格内容 */
    td, td p, td span, td strong {
      color: var(--${PROJECT_PREFIX}-theme-text-secondary) !important;
      font-size: 15px !important;
    }
    td code{
      font-size: 15px !important;
    }
  }

  /* 响应式处理 */
  @media (max-width: 768px) {
    display: block;
    th, td {
      display: block;
      width: 100%;
    }
  }
}
`
  }

  protected getHrStyles(_theme: ThemeType): string {
    const { CONTENT_HR } = this.elements

    if (!CONTENT_HR || CONTENT_HR.selector === '') {
      return ''
    }

    return `
${CONTENT_HR.selector} {
  border: 0;
  margin: 1.5rem 0;
  border-bottom: 1px solid var(--${PROJECT_PREFIX}-theme-hr-bg);
  border-top: unset !important;
  width: 100% !important;
}
`
  }

  protected getBlockQuoteStyles(_theme: ThemeType): string {
    const { CONTENT_BLOCK_QUOTE } = this.elements

    if (!CONTENT_BLOCK_QUOTE || CONTENT_BLOCK_QUOTE.selector === '') {
      return ''
    }

    return `
${CONTENT_BLOCK_QUOTE.selector} {
  background-color: var(--${PROJECT_PREFIX}-theme-quote-bg) !important;
  color: var(--${PROJECT_PREFIX}-theme-quote-text) !important;
  border-radius: 0 5px 5px 0;
  
  &:not(.${APP_DOM_SELECTOR_CONFIG.TEXT_CONTAINER.BLOCKQUOTE.value}) {
    border-left: 3px solid var(--${PROJECT_PREFIX}-theme-primary);
  }
  
  &.${APP_DOM_SELECTOR_CONFIG.TEXT_CONTAINER.BLOCKQUOTE.value} {
    padding: 2em !important;
    position: relative !important;
    border: none !important;
    font-size: 15px !important;
    
    &:before {
      content: '❝' !important;
      top: 8px;
      left: 5px;
    }
    &:after {
      content: '❞' !important;
      right: 5px;
      bottom: -5px;
    }
  }
  
  &:before, &:after {
    position: absolute !important;
    color: #cc9100 !important;
    font-size: 34px !important;
    font-weight: 700 !important;
  }
}
`
  }

  protected getImageStyles(theme: ThemeType, selector: string = ''): string {
    return `
${selector} img {
  /* 图片居中 */
  display: block;
  margin: 0 auto;
  
  /* 图片亮度和对比度调整 */
  ${theme === 'dark' ? 'filter: brightness(0.8) contrast(1.0);' : ''}
  }
${this.customImageStyles(theme)}
`
  }

  protected customImageStyles(_theme: ThemeType): string {
    return ''
  }
}
